import 'package:flutter/material.dart';
import 'package:fsharing/core/viewmodels/pages/mine/address/address_region_model.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:fsharing/ui/widgets/background_container.dart';
import 'package:fsharing/ui/widgets/round_back_button.dart';
import 'package:provider/provider.dart';

class AddressRegionArgs {
  final int level;
  final MapEntry<String, dynamic> regionItem;

  AddressRegionArgs(this.level, this.regionItem);
}

class AddressRegionPage extends StatelessWidget {
  final AddressRegionArgs args;

  AddressRegionPage({
    Key key,
    @required this.args,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => AddressRegionModel(Provider.of(context, listen: false), args),
      child: BackgroundContainer(
        child: Scaffold(
          appBar: AppBar(
            leading: RoundBackButton(),
            title: Text(args.regionItem?.value ?? '选择省份'),
          ),
          body: Consumer<AddressRegionModel>(
            builder: (context, value, child) {
              switch (value.viewState) {
                case ViewState.busy:
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                case ViewState.error:
                  return Center(
                    child: Text(value.errorMessage),
                  );
                case ViewState.success:
                  return new _ListWidget(
                    list: value.region.entries.toList(),
                  );
                default:
                  return Container();
              }
            },
          ),
        ),
      ),
    );
  }
}

class _ListWidget extends StatelessWidget {
  final List<MapEntry<String, dynamic>> list;

  const _ListWidget({
    Key key,
    @required this.list,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: list.length,
      itemBuilder: (context, index) {
        var mapEntry = list[index];
        return ListTile(
          title: Text(mapEntry.value),
          trailing: Icon(Icons.keyboard_arrow_right),
          onTap: () => _pushAddressRegion(context, mapEntry),
        );
      },
    );
  }

  Future _pushAddressRegion(BuildContext context, MapEntry<String, dynamic> mapEntry) async {
    AddressRegionModel addressRegionModel = Provider.of(context, listen: false);
    if (addressRegionModel.args.level < 2) {
      var result = await Navigator.of(context).pushNamed(
        '/address/region',
        arguments: AddressRegionArgs(addressRegionModel.args.level + 1, mapEntry),
      );
      if (result != null) {
        Navigator.of(context).pop(result);
      }
    } else {
      Navigator.of(context).pop(mapEntry);
    }
  }
}
